<template>
  <div>
    <div class="c-pf c-bg-white c-pz11 c-w100 c-maxw640">
      <new-search-bar bgSearch="c-bg-white c-pt24-i" :searchText="searchText" @search="startSearch" @cancel="startSearch"></new-search-bar>
      <my-small-tabbar id="tabhBar" :tabList="tabList" :tabIndex="courseType" @changeTab="changeType"></my-small-tabbar>
    </div>
    <div class="c-hh190"></div>
    <div class="c-bg-white c-ph24 c-pb20">
      <section v-for="(item,index) in courseList" :key="index" @click="clickCourseItem(item.courseId,item.courseType)" class="c-flex-row c-pv24 c-bd-b1">
        <!-- 左侧封面 -->
        <div class="c-ww180 c-hh120 c-flex-shrink0 c-text-hidden c-p c-br10" :class="cfg && cfg.isCopyPicture == 0 ? 'closeBig' : 'aCloseBig'">
          <CoverImg :coverSizeClass="'c-w100 c-h c-br16 c-text-hidden'" imgClass="c-br16" :coverUrl="$addXossFilter(item.courseAvatar, require('@/assets/defult270.png'))" />
          <div class="c-pa c-p-b8 c-p-r8 c-br8 c-fs18 c-fc-white c-ph5 c-hh28 c-flex-row c-flex-center c-translucent-balck50">
            {{PROD_COURSE_TYPE[item.courseType]}}
          </div>
          <vip-status :item="item"></vip-status>
        </div>
        <!-- 右侧描述 -->
        <div class="c-flex-row c-flex-column c-pl20 c-flex-1 c-justify-sb c-w0">
          <!-- 课程名称 -->
          <div class="c-fs24 c-lh34 c-text-ellipsis1 c-fc-xblack">
            <span v-if="item.isSaleOut == 0" class="c-mr6 c-fs20 c-fc-white c-ph4 c-br-tr10 c-br-bl10 c-bg-ccc">已停售</span>{{item.name}}
          </div>
          <div v-if="item.lecturer">
            <span class="iconfont icon-geren1 c-fc-sblack c-fs18 c-inlineblack c-vcAlign-middle"></span>
            <span class="c-wlecturer c-fs18 c-lh26 c-text-ellipsis1 c-textAlign-c c-br4 c-inlineblack c-vcAlign-middle c-maxw50">{{item.lecturer}}</span>
          </div>
          <div class="c-fs20 c-fc-gray" v-if="(item.courseType == 0 || item.courseType == 1) && item.previewLabel">{{item.courseType == 0 ? '支持试看' : '支持试听'}}</div>
          <div class="theme-fc c-flex-row" :class="item.payType == 1 ? 'c-fs24 c-lh24' : 'c-fs30 c-lh32'">
            <div class="c-fc-xmlred c-fs0 c-flex-row c-aligni-end c-pr10">
              <span class="c-fs20 c-fw600"v-if="item.payType == 2">{{'￥' | iosPriceFilter}}</span>
              <span class="c-fw600" :class="checkCnPrice(item.payType, item.price, 5) ? 'c-fs22' : 'c-fs26'">{{item.payType | priceValueFilter(item.price, 5, item.optimal, 'index')}}</span>
              <span v-if="isShowcrossedPrice(item)" class="c-fs24 c-fc-gray c-text-decoration-through c-mh4">￥{{getCrossedPrice(item)}}</span>
            </div>
            <div v-if="enableShowModuleView == 1 || !(enableHiddenModules && enableHiddenModules.includes(ckFrom))" class="c-flex-grow1 c-w0 c-textAlign-r">
              <span class="c-flex-grow1 c-fs20 c-lh28 c-w0 c-textAlign-r c-fc-gray">{{item.plays | formatNumber}}人{{item.courseType == 1 ? '收听' : '看过'}}</span>
            </div>
          </div>
        </div>
      </section>
    </div>
    <loading-status-tem :showLoading="isLoading" :noMoreData="is_page == false && (courseList && courseList.length > 0)" :noData="courseList.length == 0" :noDataText="'暂无结果'"></loading-status-tem>
    <template v-if="companyAuth && companyAuth.companyNav">
      <nav-bottom-bar :itemIndex="40" v-for="(item,index) in companyAuth.companyNav" :key="index" v-if="item.navType == 40"></nav-bottom-bar>
    </template>
  </div>
</template>

<script>
import NavBottomBar from "@/components/templates/common/navBottomBar.vue";
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import vipStatus from '@/components/templates/common/vipStatus.vue'
import CoverImg from '@/components/templates/common/coverImg.vue';
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import { utilJs } from "@/utils/common.js";
let isVipCourse = false; //是否vip课程
let catId = ""; //课程分类ID
let sort = ""; //排序类型
let permition = ""; //观看权限
let sortType = 0;
let fullPath = '';
export default {
  name: "CourseList",
  components: {
    loadingStatusTem,
    MySmallTabbar,
    vipStatus,
    CoverImg,
    newSearchBar,
    NavBottomBar
  },
  props: [],
  computed: {
    // 判断显示划线价格
    isShowcrossedPrice() {
      return function(item) {
        return !this.$isWxAppIos() && item.crossedPrice && Number(item.crossedPrice) > 0;
      }
    },
    // 获取划线价格
    getCrossedPrice() {
      return function(item) {
        return item.crossedPrice;
      }
    }
  },
  data() {
    return {
      PROD_COURSE_TYPE: global.prodCourseType,
      is_page: false,
      page: 1,
      limit: 10,
      courseType: 3,
      searchText: "",
      courseList: [],
      isLoading: false,
      tabList: [{
        title: '全部',
        index: 3,
      }, {
        title: '视频',
        index: 0,
      }, {
        title: '音频',
        index: 1,
      }, {
        title: '图文',
        index: 2,
      }],
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      cfg: JSON.parse(localStorage.getItem("cfg")),
      enableShowModuleView: localStorage.getItem("cfg") ? JSON.parse(localStorage.getItem("cfg")).enableShowModuleView : 1,
      enableHiddenModules: localStorage.getItem("cfg") ? JSON.parse(localStorage.getItem("cfg")).enableHiddenModules : [],
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
    this.wechatShare();
  },
  methods: {
    checkCnPrice(payType, price, prodType) {
      return utilJs.checkCnPrice(payType, price, prodType)
    },
    iosAppRouteChange(toPath) {
      if (utilJs.isIOSApp()) {
        window.webkit.messageHandlers.iosWechatRoute.postMessage(toPath);
      } else if (utilJs.isAndoridNewApp()) {
        let data = {
          path: toPath
        }
        window.androidWechatRoute.doAction(JSON.stringify(data))
      } else {
        this.$routerGo(this, "push", { path: toPath });
      }
    },
    //更换类别
    changeType(tabIndex) {
      //防止快速切换，数据展示错误
      if (this.isLoading) {
        return;
      }
      if (this.courseType != tabIndex) {
        this.page = 1;
        this.courseList = [];
      }

      this.courseType = tabIndex;
      this.getMore();
      let mapType = {
        3: 0,
        0: 1,
        1: 2,
        2: 3
      };
      let srot = `&sortType=${sortType}`;
      let newUrl = `${window.location.href.split("#")[0]}#/homePage/course/courseList?type=${mapType[this.courseType]}${srot}`;
      history.replaceState("homework", "", newUrl);
    },
    //通过名称模糊搜索
    startSearch(e) {
      // this.courseType = 3;
      this.page = 1;
      this.courseList = [];
      utilJs.toPageScrollTop();
      this.searchText = e.searchValue;
      this.getMore();
    },
    //分页获取课程列表
    getMore() {
      if (!this.isLoading) {
        this.isLoading = true;
        let $this = this;
        utilJs.getMethod(
          global.apiurl +
          "courses?name=" +
          this.searchText +
          "&type=" +
          this.courseType +
          "&page=" +
          this.page +
          "&limit=" +
          this.limit +
          "&isVip=" +
          isVipCourse +
          "&catId=" +
          catId +
          "&sort=" +
          sort +
          "&p=" +
          permition +
          "&sortType=" +
          sortType,
          function (res) {
            if ($this.page == 1) {
              $this.courseList = res.data;
            } else {
              let list = res.data;
              $this.courseList = $this.courseList.concat(list);
            }
            $this.page = res.data && (res.data.length >= $this.limit) ? ($this.page + 1) : $this.page;//res.current_page < res.last_page ? $this.page + 1 : $this.page;
            $this.is_page = res.data && (res.data.length >= $this.limit) ? true : false;//res.current_page < res.last_page ? true : false;
            $this.isLoading = false;
          }
        );
      }
    },
    //课程详情页面
    clickCourseItem(courseId, type) {
      let courseMap = {
        0: "video",
        1: "voice",
        2: "imgText"
      };
      let pushUrl = `/homePage/course/${courseMap[type]}?courseId=${courseId}&ckFrom=${global.ckFrom.course}&extId=-1`;
      this.iosAppRouteChange(pushUrl);
    },
    //分享
    wechatShare: function () {
      let title = "课程列表"; //window.localStorage.getItem("shareTitle");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?type=0&refereeId=${localStorage.getItem("userId")}`;
      utilJs.wechatConfig(shareUrl, title, "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      let title = "课程列表"; //window.localStorage.getItem("shareTitle");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?type=0&refereeId=${localStorage.getItem("userId")}`;
      utilJs.appShareTrue(title, "", shareUrl, "");
    },
    //下滑获取更多
    windowScrollFunction: function () {
      let that = this;
      utilJs.handleLoading(function () {
        if (that.is_page == true) {
          that.getMore();
        }
      });
    },
    initData: function () {
      sortType = this.$route.query.sortType || 0;
      isVipCourse = this.$route.query.isVip || "";
      catId = this.$route.query.catId || ""; //课程分类ID
      sort = this.$route.query.sort || ""; //排序类型
      permition = this.$route.query.permition || ""; //观看权限
      let selectType = this.$route.query.type || 0;
      let mapType = {
        0: 3,
        1: 0,
        2: 1,
        3: 2
      };
      this.searchText = "";
      this.courseType = mapType[selectType];
      this.page = 1;
      this.is_page = false;
      this.courseList = [];
      this.isLoading = false;
      this.getMore();
      //window.addEventListener('scroll', this.windowScrollFunction);
    }
  },
  activated() {
    let refresh = false;
    if (fullPath != this.$route.fullPath) {
      refresh = true;
    }
    fullPath = this.$route.fullPath;
    if (this.$route.query.isVip) {
      setDocumentTitle("VIP课程");// eslint-disable-line
    } else {
      setDocumentTitle("精品课程");// eslint-disable-line
    }
    let scrollTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
    let clientHeight = document.body.clientHeight && document.documentElement.clientHeight ? Math.min(document.body.clientHeight, document.documentElement.clientHeight) : Math.max(document.body.clientHeight, document.documentElement.clientHeight);
    let scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    let selectType = this.$route.query.type || 0;
    let mapType = {
      0: 3,
      1: 0,
      2: 1,
      3: 2
    };
    if (!((scrollTop + clientHeight < scrollHeight) && this.courseList && this.courseList.length > 0 && this.page != 1 && this.courseType == mapType[selectType]) || refresh) {
      this.initData();
    }
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    //this.is_page = false;
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
</style>
